<?php
/**
 * @copyright SYS Company
 * @author : Mr  Nguyễn Hoàng Long
 * @version : 1.0
 * @name : CRUD Class
 * @todo:  Lớp  mở rộng của CModule. Thao tác danh sách, sửa, xóa cơ sở.
*/
class Messenger extends CModule{
	public $discount;
	public $user;

	function init() {
		$this->user = user();
	}
	function getBanner($page) {
		$cache_name = 'messenger_banner';
		if (!($banner=CSystem::$cachedata->get($cache_name))) {
			if(!($banner = CTable('banner')->select(
				EAnd(
					EEqual('in_page',$page),
					EEqual('region','center')
				),
				array('items_per_page'=>1)
			))) {
				$banner = array('src'=>'');
			} else {
				if (@$banner['src']['0']!='/') $banner['src'] = '/'.$banner['src'];
				if($banner['banner_type']=='flash') {
					$banner['src'] = '<embed style="width:338px;height:323px;" wmode = "transparent" src="'.$banner['src'].'"/>';
				} else {
					if($banner['banner_type']=='image')
						$banner['src'] = '<img style="width:338px;height:323px;" src="'.$banner['src'].'"/>';
					else
						if($banner['banner_type']=='iframe')
							$banner['src'] ='<iframe  style="width:338px;height:323px; border:none;" src="'.$banner['src'].'"  ></iframe> ';
						else
							$banner['src'] = '<div style="width:338px; height:323px;overflow:hidden" >'.$banner['src'].'</div>';
				}
			}
			CSystem::$cachedata->set($cache_name, $banner, 600);
		}
		return $banner;
	}

	function getCommonInfor() {
		$cache_name = 'messenger_non_seller';
		if (!($ret = CSystem::$cachedata->get($cache_name))) {
			$zone = CTable('zone')->select_all(EGT('status',0), array('items_per_page'=>100));
			$districts=CTable('district_shipping_fee')->fields('id,name,vas_fee,addition_fee,province_id')->select_all();
			$ret = array(
				'zones'=> $zone,
				'districts'=>$districts
			);
			CSystem::$cachedata->set($cache_name, $ret, 86400);
		}
		return $ret;
	}

	function getSellerInfor() {
		$cache_name = 'messenger_seller_infor';
		$portal = portal();
		if (!($ret = CSystem::$cachedata->get($cache_name))) {
			$districts=CTable('district_shipping_fee')->fields('id,name,vas_fee,addition_fee,province_id')->select_all();
			$ret = array();
			$ret['districts_json'] = CString($districts)->json();
			$ret['locations'] = CString(CTable('location')->select_all())->json();
			$ret['transport_fee'] = CString(CTable('transport_fee')->select_all())->json();
			$ret['zone_location'] = CString(CList(CTable('zone_location')->select_all())->extract_id('zone_id'))->json();			
			CSystem::$cachedata->set($cache_name, $ret, 86400);
		}
		//Khoanb Edit 31.08.09
		$cacheJsLocation = 'var locations = {\'districts_json\': '.$ret['districts_json'].', \'locations\': '.$ret['locations'].', \'transport_fee\': '.$ret['transport_fee'].', \'zone_location\': '.$ret['zone_location'].'}';
		$dirCacheLocation = 'publish/'.$portal->id.'/location';
		if(!is_dir($dirCacheLocation)) {
			@mkdir($dirCacheLocation, 0777);
		}
		$hashFile = md5($cacheJsLocation);
		if(!CFile::exists($dirCacheLocation.'/location.'.$hashFile.'.js')) {
			file_put_contents($dirCacheLocation.'/location.'.$hashFile.'.js', $cacheJsLocation);
		}
		$ret['ver'] = $hashFile;
		
		
		$attr_name = 'seller_msg';
		if (!($report=session($attr_name))) {
			$report = CTable('seller_report')
				->fields('sum(total_seller_fee) as seller_fee, sum(total_success_amount) as success_amount')
				->select(EAnd(EEqual('seller_id',$this->user->id)),EEqual('month',EInt(date('m'))),EEqual('year',EInt(date('Y'))));
			session($attr_name, $report);
		}
		$ret += $report;
		
		return $ret;
	}

	function draw() {
//		if (!$this->user->is_login()) return;
		// nếu login
		if ($this->user->is_login()) {
			$isLogin = true;
			$userId = $this->user->id;
		} else {
			$isLogin = false;
			$userId = session('userId');
		}
		$isSaleman = $isLogin?($this->user->is_register_salesman == 2):false;
		$common_infor = $this->getCommonInfor();
		if ($isSaleman) {
			$seller_infor = $this->getSellerInfor();
		} else {
			$seller_infor = array();
		}

		$page=$isSaleman?'salesman_chat':'customer_chat';
		$banner = $this->getBanner($page);
		if ($isSaleman && $isLogin) {
			$condition=EAnd(EEqual('is_seller',0),EEqual('user_id',$this->user->id), ENE('friend_id',$this->user->id));
		} else if($isLogin) {
			$condition=EAnd(EEqual('is_seller',1),EEqual('user_id',$this->user->id), ENE('friend_id',$this->user->id));
		}
		/*
		$friends = $this->getCacheData(
			array('table' => 'friend', 'condition' => $condition, 'cache_name' => "friend_list_{$this->user->id}_".CPortal::$estore_id));
		*/
		if (!($friends = session('friend_list')) && $isLogin) {
			$friends = CTable('friend')->fields('friend_id')->select_all($condition, array('items_per_page'=>50));
			session('friend_list', $friends);
		}else{
			$friends =array();
		}

		$product_id = request('product_id', '');
		$this->extend_layout('layout',array(
			'friends'=>$friends,
			'userId'=>$userId,
			'is_seller'=>$isSaleman?1:0,
			'product_id' => $product_id,
			'product' => (intval($product_id) and $product = CTable('product')->select($product_id))?$product : array(),
			'banner' => $banner['src'])
			+ $common_infor
			+ $seller_infor
		);
 	}

 	function get_discount_condition() {
 		$this->discount=false;
 		$previous_day= time()-24*3600;
 		$condition = EAnd(EGT('date',$previous_day),ELTE('date',time()));
		$promotion = CTable('daily_promotion')->select($condition);
		if(is_array($promotion))
		{
			$this->discount=$promotion['max_number_order']>$promotion['number_order'];
		}
		return $this->discount;
 	}

	function on_search_product() {
		$keyword=strip_tags(trim(request('keyword')));
		$condition = EAnd(ELike('name',$keyword), EGT('min_price', EInt(0)), EGT('price', EInt(0)), EGT('market_price', EInt(0)), EGT('floor_price', EInt(0)), EGT('quantity', EInt(0)), EGT('status', EInt(0)),EEqual('reference_id',EString('')));
		$products=CTable('product')->select_all($condition,array('field'=>'name,id', 'items_per_page'=>10));
		if ($products) {
			$this->extend_layout('list',(array('products'=>$products)));
		} else {
			echo 0;
		}
	}

	function on_select_user() {
		if($id = request('user_id') and $user = CTable('user')->select($id,array('fields'=>'id,full_name,zone_id,phone,ym,skype,address,avatar_url'))) {
			echo CString($user)->json();
		} else if(strpos(request('user_id'),'Guest_') !== false) {
		  	echo CString(array('id'=>request('user_id'),'full_name'=>'Guest','zone_id'=>0,'zone_id'=>'','ym'=>'','skype'=>'','address'=>'','address'=>''))->json();
		} else {
			echo '{}';
		}
	}

	function on_select_product() {
		if(!($userId=request('userId'))) {
			return;
		}
		if(request('product_id') and $product = CTable('product')->fields(
			'id, name, price, min_price, market_price, cache_all_properties, colors, image, thumbnail, large, small, media, flash, category_id, tax, discount_percent, discount_maximum_items, discount_items, discount_start_date, discount_end_date,pack_weight,reference_id,substitute_id,quantity')
			->select(request('product_id')) and $this->user->is_login())
		{
			if(!$product['thumbnail'] and $product['reference_id'] and $reference = CTable('product')->select(array('code'=>$product['reference_id']))) {
				$product['thumbnail'] = $reference['thumbnail'];
				$product['large'] = $reference['large'];
				$product['image'] = $reference['image'];
				$product['medium'] = $reference['medium'];
				$product['images'] = CTable('product_media')->fields('id, large, thumbnail')->select_all(array('product_id'=>$reference['id']));
			} else {
				$product['images'] = CTable('product_media')->fields('id, large, thumbnail')->select_all(array('product_id'=>$product['id']));
			}

			if($product['colors']) {
				$product['colors'] = explode(',',$product['colors']);
			}
		}
		$productDetail = new CProductDetail(request('product_id'));
			$product['price']=$productDetail->getDisplayPrice();
		echo CString($product)->json();
	}


	function on_accept() {
		$price=request('price')/1000;
		$product_id=request('product_id');
		$seller_id=request('sellerId');
		if($product = CTable('product')->select($product_id)) {
			if($product['quantity']>=1) {
				$this->get_discount_condition();
				$discount_percent=(($this->discount) and ($product['discount_items']<$product['discount_maximum_items']) and($product['discount_start_date']<time())
		and($product['discount_end_date']>time()))?$product['discount_percent']:0;
				$item=array(
					'id'=>$product_id,
					'price'=>$price,
					'seller_id'=>$seller_id,
					'quantity'=>1,
					'code'=>$product['code'],
					'taxp'=>$product['tax'],
					'tax'=>($product['tax']*$price)/100,
					'name'=>$product['name'],
					'pack_weight'=>$product['pack_weight'],
					'weight'=>$product['weight'],
					'max_quantity'=>$product['quantity'],
					'image'=>$product['image'],
					'code'=>$product['code'],
					'min_price'=>$product['min_price'],
					'discount_percent'=>$discount_percent,
		 			'shipping_fee'=>0,
		 			'store_id'=>'',
					'portal_id'=>$product['portal_id'],
					'portal_path'=>CPortal::get_portal_path($product['portal_id'])
				);
				$shopping_cart = is_array($this->user->shopping_cart())?$this->user->shopping_cart():array();
				//$condition=EAnd(EEqual('id',$product_id), EEqual('seller_id',$item['seller_id']), EEqual('price',$item['price']));
				$duplicate=0;
				foreach ($shopping_cart as $key=>$value) {
					if (($value['id']==$item['id'])&&($value['seller_id']==$item['seller_id']) && ($value['price']==$item['price'])) {
						$duplicate=1;
						$shopping_cart[$key]['quantity']++;
					}
				}
				if(!$duplicate) {
					array_push($shopping_cart,$item);
				}
				$this->user->shopping_cart($shopping_cart);
				cookie('shopping-cart-total-items',sizeof($shopping_cart));
				echo $duplicate;
			} else {
				echo 0;
			}
		} else {
			echo 0;
		}
	}

	function on_make_friend() {
		if ($friend_id = request('id')) {
			$user = CTable('user')->select($this->user->id);
			$friend = CTable('user')->select($friend_id);
			if (!$user || !$friend) {
				echo 0;
				return;
			}
			$this->make_friend($user, $friend, 0);
			$this->make_friend($friend, $user, 1);
		}
 	}

	function make_friend($user, $friend, $status) {
		if(!CTable('friend')->select(EAnd(EEqual('user_id',$user['id']),EEqual('friend_id',$friend['id'])))) {
			CTable('friend')->save(array(
				'user_id'=>$user['id'],
				'friend_id'=>$friend['id'],
				'avatar'=>$friend['avatar_url'],
				'online_status'=>$friend['online_status'],
				'blast'=>$friend['blast'],
				'is_seller'=>(isset($friend['is_register_salesman']) and $friend['is_register_salesman'] == 2)?1:0,
				'time'=>time(),
				'status'=>$status
			));
			$total_friend=CTable('friend')->count(EEqual('user_id', $user_id));
			CTable('user')->update(array('total_friend'=>$total_friend),$user_id);
			//$this->user->recache($user_id);
			echo 1; //Thêm thành công
		} else {
			echo 0;
		}
	}

	function getCacheData($options = array()) {
		if( is_array($options) && count($options) > 0
			&& isset($options['table']) && $table = $options['table']
			&& isset($options['cache_name']) && $cache_name = $options['cache_name']
		) {
			$cache_time = isset($options['cache_time'])?$options['cache_time']:86400; // 1 day
			$condition = isset($options['condition'])?$options['condition']:'';

			if (!($value = CSystem::$cachedata->get($cache_name.$condition))) {
				if(!isset($options['one_row'])) {
					if(isset($options['sort'])) {
						$value = CTable($table)->select_all($condition, $options['sort']);
					} else {
						$value = CTable($table)->select_all($condition);
					}
				} else {
					if(isset($options['sort'])) {
						$value = CTable($table)->select($condition,	$options['sort']);
					} else {
						$value = CTable($table)->select($condition);
					}
				}
				CSystem::$cachedata->set($cache_name.$condition, $value, $cache_time);
			}
			return $value;
		}
	}
/*----------------------------------khuyennv--------------------------------------------------------*/
	/**
	* tạo id Guest
	* xóa cache các tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	function on_createGuestNick() {
		$userId = 'Guest_'.rand(0,999);
		$cacheName = 'Guest_vimua_no_login';
		if ($datas = CSystem::$cachesession->get($cacheName)) {
			while (isset($datas[$userId])) {
				$userId = 'Guest_'.rand();
			}
		}
		foreach ($datas as $Uid=>$time) {
			if ($time+5*60 < time()) {
				unset($datas[$Uid]);
			}
		}

		echo $userId;
	}
	/**
	* xóa cache các tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	static function genGuestNick() {
		$cacheName = 'Guest_vimua_no_login';
		if(!session('userId')) {
			$userId = 'Guest_'.rand(0,9999);
			if ($datas = CSystem::$cachesession->get($cacheName)) {
				while (isset($datas[$userId])) {
					$userId = 'Guest_'.rand(0,9999);
				}
				$datas[$userId] = time();
				// clear cache
				foreach ($datas as $Uid=>$time) {
					if ($time+20*60 < time()) {
						unset($datas[$Uid]);
					}
				}
			} else {
				$datas = array();
				$datas[$userId] = time();
			}
			CSystem::$cachesession->set($cacheName, $datas);
			session('userId',$userId);
		}else{
			$userId = session('userId');
			if ($datas = CSystem::$cachesession->get($cacheName)) {
				if (isset($datas[$userId]) and ($datas[$userId] + 20*60 < time())) {
					unset($datas[$userId]);
					$datas = CSystem::$cachesession->set($cacheName,$datas);
					session('userId','');
					self::genGuestNick();
				}
			}
		}
	}
	/**
	* xóa cache các tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	function on_clearListCustomer() {
		$cacheName = 'Guest_vimua_no_login';
		CSystem::$cachesession->set($cacheName, array());
		echo '\nEnd';
	}
	/**
	* Thêm một tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	function on_getListCustomer() {
		$cacheName = 'Guest_vimua_no_login';
		if ($datas = CSystem::$cachesession->get($cacheName)) {
			print_r($datas);
		}
		echo '\nEnd';
	}
	/**
	* Thêm một tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	function on_addCustomer() {
		if($id = request('id')) {
			$cacheName = 'Guest_vimua_no_login';
			if ($datas = CSystem::$cachesession->get($cacheName)) {
				$datas[$id] = time();
			}else{
				$datas = array();
				$datas[$id] = time();
			}
			print_r($datas);
			CSystem::$cachesession->set($cacheName, $datas);
		}
	}
/**
	* xóa một tài khoản Guest vào danh sách guest online
	*
	* @param String $id id cần add vào danh sách ngưoi mua online
	*
	* */
	function on_delCustomer() {
		if($id = request('id')) {
			$cacheName = 'Guest_vimua_no_login';
			if ($datas = CSystem::$cachesession->get($cacheName)) {
				if (isset($datas[$id])) {
					unset($datas[$id]);
				}
				CSystem::$cachesession->set($cacheName, $datas);
			}
		}
	}
	function on_refresh() {
		if($id = request('id')) {
			$cacheName = 'Guest_vimua_no_login';
			if ($datas = CSystem::$cachesession->get($cacheName)) {
				if(isset($datas[$id])) {
					$datas[$id]=time();
				}
			}
			CSystem::$cachesession->set($cacheName, $datas);
		}
	}
	function on_listcus() {
		$buddyList = request('buddyList');
		print_r(json_decode($buddyList));
		//error_log('end===> '.$buddyList."\n<br>", 3, 'c:\delfolder.htm');
	}
}